<template>
	<view class="isImageBackGourd" :class="{'no-scroll': isPopupOpen}">
		<view class="isIconImage" @click="goBack">
			<image class="isBackIcon" src="../../../static/bar/返回.png" mode=""></image>
		</view>
		<image class="isImageBackGourdiMAGE" :src="imageUrl+backImage" mode="aspectFill"></image>
		<view class="isALLbox">
			<view class="isTitle">
				<view class="isTitleIndex">
					成都
					<view v-for="(item,index) in dataArray" :key="index">
						-{{item.ScenicName}}-
					</view> 行程计划
				</view>
				<view class="isTitleIndexBox" @click="toTxMap">
					<image class="icon"
						src="https://file.whshiyuan.cn:9000/toopu/compressed/8351731382254_compressed_img.png" mode="">
					</image>
					地图
				</view>
			</view>
			<view class="isSelectButton">
				<view class="isSelectButtonItemBox" @click="isfalse">
					<view v-if="!isselect" class="isNo"></view>
					<image v-if="isselect" class="isselect"
						src="https://file.whshiyuan.cn:9000/toopu/compressed/9641731381558_compressed_img.png" mode="">
					</image>
					<view class="isIndex">需要领队</view>
				</view>
				<view class="selectPeleTiem" @click="selectBottomDay">
					{{selectData}} >
				</view>
			</view>
			<selectDayVue :baseData='allDayItem' @isSelect='isSelect'></selectDayVue>
			<view class="" v-if="AllDay==0">
				<movableViewVue @deleDay='deleDay' @addDay='toAddDay' @isNowData='isNowData' :isAllDataSele='dataArray'>
				</movableViewVue>
			</view>
			<view class="" v-else>
				<scroll-view scroll-y="true" class="scroll-Y">
					<view class="text-box">
						行程参考
						<text style="font-size: 20rpx;color: #737373;">(此行程来自以下商品)</text>
					</view>
					<view class="goods-card" @click="toDetail(TripInfo.shop_info.shop_id)">
						<image class="card-img" :src="imageUrl + TripInfo.shop_info.cover_image" mode="aspectFill">
						</image>
						<view class="card-right">
							<text class="title">{{TripInfo.shop_info.title}} | {{TripInfo.shop_info.subtitle}}</text>
							<text class="description">{{TripInfo.shop_info.description}}</text>
							<view class="price-box">
								<text class="price">￥{{TripInfo.shop_info.display_price}}</text>
								<text class="suffix">/起</text>
							</view>
						</view>
					</view>
					<view class="collapsec-box ">
						<view class="Close-box">
							<view class="Close-lt Close-lt-open">
							</view>
							<view class="Close-rt">
								<view class="lt-hd">
									<view class="hd-title hd-title-open">
										<text>{{TripInfo.day_arrangement_info.trip_detail_content}}</text>
									</view>
									<view class="hd-open">
										<image class="close"
											src="https://img.js.design/assets/img/66ce933e8afcb6064d0afdc3.png#53aa147d3e6b380a2691caf59801a977"
											mode=""></image>
									</view>
								</view>
								<view class="lt-fd">
								</view>
							</view>
						</view>
						<view class="content-container">
							<view class="content-box"
								v-for="(item_a,index_A) in TripInfo.day_arrangement_info.trip_day_detail_son_list"
								:key="index_A">
								<view class="title">{{item_a.trip_day_detail_title}}</view>
								<view class="content">{{item_a.trip_day_detail_content}}</view>
							</view>
						</view>

					</view>
					<view class="kongbai" style="height: 15vh;">

					</view>
				</scroll-view>
			</view>
			<selectNumberTimeVue @selectEmits='selectEmits' @openPopup="handlePopupOpen" @closePopup="handlePopupClose"
				:allNumberitem='allNumberitem' ref="isNumTime"></selectNumberTimeVue>

		</view>
		<bottomNavBarVue :isSelect='isData' :backImage="backImage" @subMit="subMittoTripDetails"></bottomNavBarVue>
	</view>
</template>

<script setup>
	import {
		imageUrl
	} from '@/config/request/request';
	import AddDayPoupoVue from './components/AddDayPoupo.vue';
	import selectNumberTimeVue from './components/selectNumberTime.vue';
	import bottomNavBarVue from './components/bottomNavBar.vue';
	import movableViewVue from './components/movableView.vue';
	import selectDayVue from './components/selectDay.vue';
	import {
		useStore
	} from "../../../store/store.js"
	import {
		customStore
	} from "../../../store/custom"
	import {
		Getorder,
		Getloops,
		GetTripSenceinfo,
		orderBackPost
	} from '@/config/API/Customize';
	import {
		nextTick,
		ref,
		watchEffect,
		watch
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	const {
		getScienceData,
		resetScienceData
	} = useStore();
	const {
		setCustomData
	} = customStore()
	const isPopupOpen = ref(false);

	const isselect = ref(true)
	const isNumTime = ref(null)
	const AllDay = ref(0)
	const dataArray = ref([])
	const selectData = ref('请选择人数和抵达日期')
	const isData = ref()
	const allDayItem = ref([{
		day: 0,
		Day: '总',
		ScenicId: 0,
		isSelect: true // 默认选中“总”
	}])
	const detailTripinfo = ref({})
	//用户id
	const user_id = ref()
	//最终提交的数据
	const submitinfo = ref({
		order_title: '',
		departure_location: '成都',
		arrival_time: '',
		return_location: '成都',
		order_remark: '',
		is_need_butler: 0,
		user_id: user_id.value,
		user_name: '',
		user_num: '',
		person_info: {
			adult: 0,
			bin_kid: 0,
			middle_kid: 0,
			small_kid: 0,
			old_man: 0,
			hmt_person: 0,
			foreigner: 0
		},

	})
	const selectEmits = (item) => {
		const totalPeople = calculateTotalPeople(item)
		selectData.value = `总人数:${totalPeople}|日期:${item.arrival_time}`
		isData.value = item
		isPopupOpen.value = false;
	}

	function calculateTotalPeople(item) {
		// 定义哪些属性应该计入总人数
		const peopleFields = ['adult', 'small_kid', 'middle_kid', 'bin_kid', 'foreigner', 'hmt_person', 'old_man'];
		// 计算总人数
		let totalPeople = 0;
		for (let field of peopleFields) {
			if (item.hasOwnProperty(field)) {
				totalPeople += Number(item[field]) || 0; // 确保值是数字，并处理可能的 null 或 undefined
			}
		}
		return totalPeople;
	}
	const allNumberitem = ref()
	// 删除一天时更新 allDayItem
	const deleDay = (day) => {
		const filterdata = allDayItem.value.filter(item => item.Day !== day);
		allDayItem.value = [filterdata[0], ...filterdata.slice(1).map((item, index) => ({
			...item,
			day: index + 2,
			Day: index + 2
		}))];

	};
	// 处理新景点选择的方法
	const handleNewScenicSelection = (newScenic) => {
		const lastItemIndex = allDayItem.value.length - 1;
		const newDay = lastItemIndex + 1;

		const newItem = {
			Day: newDay,
			ScenicName: newScenic.scienc_name,
			ScenicId: newScenic.science_id,
			Longitude: newScenic.longitude,
			Latitude: newScenic.latitude,

		};
		// 更新 dataArray 和 allDayItem
		dataArray.value.push(newItem);
		allDayItem.value.push({
			day: newDay,
			Day: newDay,
			ScenicId: newScenic.science_id,
			isSelect: false // 新增项默认不选中
		});

	};
	//刚进入页面存参数
	const optionsData = ref()
	const getData = async (options) => {
		const userId = uni.getStorageSync('userInfo').id
		user_id.value = userId
		const data = await Getorder(options.selecttrip, userId)
		nextTick(async () => {
			backImage.value = data.data.order_img
			dataArray.value = data.data.order_info
			dataArray.value.forEach(item => {
				allDayItem.value.push({
					day: item.Day,
					Day: item.Day,
					ScenicId: item.ScenicId
				})
			})
		})
	}

	// 更新 allDayItem 的顺序，使其与 dataArray 中的顺序一致
	const updateAllDayItemOrder = () => {
		const updatedAllDayItem = dataArray.value.map((item, index) => ({
			day: index + 1,
			Day: index + 1,
			ScenicId: item.ScenicId, // 如果需要，可以添加其他属性
			isSelect: false // 默认不选中
		}));

		// 保留第一个元素（假设是“总”），然后拼接上更新后的项
		allDayItem.value = [allDayItem.value[0], ...updatedAllDayItem];

	};
	const backImage = ref('https://img.js.design/assets/img/6254201212ce175b0adee406.png')
	onLoad(async (options) => {
		optionsData.value = options
		getData(options)
	})
	onShow(async () => {
		// 使用 nextTick 确保 DOM 更新完成后处理数据
		await nextTick();
		// 直接检查 getScienceData 的值并处理
		if (getScienceData.value !== null) {
			handleNewScenicSelection(getScienceData.value);
			resetScienceData(); // 处理完后重置 getScienceData
		}
		// 强行触发 @isSelect 事件，确保数据显示出来，并定位到最后一个有效项
		const validItems = allDayItem.value.filter(item => item.Day !== '总');
		if (validItems.length > 0) {
			const lastValidIndex = validItems.length - 1;
			isSelect(lastValidIndex + 1, validItems[lastValidIndex], true);
		}
	});
	//提交结果映射是否需要领队的0/1值
	function boolToInt(bool) {
		return bool ? 1 : 0;
	}


	// 监听 dataArray 的变化并更新 allDayItem
	watch(dataArray, (newVal) => {
		updateAllDayItemOrder();
	}, {
		deep: true
	});

	const isfalse = () => {
		isselect.value = !isselect.value
	}
	const toTxMap = () => {
		console.log('allDayItem', allDayItem.value);
		const scenicIds = allDayItem.value.slice(1).map(item => item.ScenicId).join(',');
		console.log('scenicIds', scenicIds);
		uni.navigateTo({
			url: `/homeSubpages/TXmap/TXmap?id=3&scenicIds=${encodeURIComponent(scenicIds)}`
		})
	}
	// 跳转到添加天数页面，并传递回调函数
	const toAddDay = () => {
		uni.navigateTo({
			url: `/homeSubpages/TXmap/TXmap?id=2`
		});
	};

	const goBack = () => {
		uni.navigateBack()
	}
	const selectBottomDay = () => {
		isNumTime.value.showPopup()
	}
	// 查询行程介绍的请求方法
	const GetTripInfo = async (senceId) => {
		try {
			const res = await GetTripSenceinfo(senceId, user_id.value)
			if (res.code == 200) {
				return res.data
			} else {
				uni.showToast({
					title: '网络异常',
					icon: "error"
				})
			}
		} catch (e) {
			//TODO handle the exception
			uni.showToast({
				title: '网络异常',
				icon: "error"
			})
		}
	}
	//选中时的存放数行程及商品数据的响应式
	const TripInfo = ref({})
	// 选中day1之类的方法
	const isSelect = async (inx, item, forceUpdate = false) => {
		AllDay.value = inx
		if (item.ScenicId) {
			const res = await GetTripInfo(item.ScenicId)
			TripInfo.value = res
		}
		// 更新 allDayItem 的选中状态
		if (forceUpdate) {
			allDayItem.value.forEach(i => i.isSelect = false);
			item.isSelect = true;

			// 通知子组件更新滚动位置
			// emits('updateScrollPosition', inx - 1); // 假设 "总" 是第0项，所以这里减1
		}
	}
	//跳转到商品
	const toDetail = (id) => {
		const url = `/homeSubpages/ProductDetails/index?ShopId=${id}`;
		uni.navigateTo({
			url: url
		})

	}

	let isProcessing = false; // 用于跟踪是否正在处理

	//提交定制订单
	const subMittoTripDetails = async (backImage) => {
		if (isProcessing) return; // 如果已经在处理，则直接返回，防止重复点击
		try {
			isProcessing = true; // 标记为正在处理
			// 显示加载指示器
			uni.showLoading({
				title: '正在创建',
				mask: true // 注意这里应该是一个布尔值而不是字符串
			});
			// // 模拟异步操作（如果需要实际的异步逻辑，请替换这里的延时）
			// await new Promise(resolve => setTimeout(resolve, 500));

			if (dataArray.value) {
				// 初始化 arrangement_info 数组
				const res = dataArray.value.map(item => ({
					day: item.Day,
					scenic_id: item.ScenicId,
					scenic_name: item.ScenicName
				}));
				//拼接出定制订单的标题

				const scenicNames = dataArray.value.map(item => item.ScenicName).join('-');

				submitinfo.value.arrangement_info = res
				submitinfo.value.arrival_time = isData.value.arrival_time
				submitinfo.value.is_need_butler = boolToInt(isselect.value)
				submitinfo.value.order_remark = isData.value.order_remark
				submitinfo.value.order_title = `成都-${scenicNames}`
				submitinfo.value.user_id = user_id.value
				submitinfo.value.user_name = isData.value.user_name
				submitinfo.value.user_num = isData.value.user_num
				submitinfo.value.person_info.adult = isData.value.adult
				submitinfo.value.person_info.bin_kid = isData.value.bin_kid
				submitinfo.value.person_info.foreigner = isData.value.foreigner
				submitinfo.value.person_info.hmt_person = isData.value.hmt_person
				submitinfo.value.person_info.middle_kid = isData.value.middle_kid
				submitinfo.value.person_info.old_man = isData.value.old_man
				submitinfo.value.person_info.small_kid = isData.value.small_kid
				console.log('提交', submitinfo.value);
				setCustomData(submitinfo.value)
				uni.navigateTo({
					url: `/homeSubpages/customize/TripDetails/TripDetails?backImage=${backImage}`
				})
				// 注意：uni.navigateTo 可能会立即改变页面，因此 hideLoading 应该放在 navigateTo 之前或确保在新页面加载后调用
				uni.hideLoading();
			}
		} catch (error) {
			// 错误处理
			console.error('创建行程失败:', error);
			uni.showToast({
				title: '系统错误',
				icon: 'none'
			});
			uni.hideLoading();
		} finally {
			// 确保无论如何都会重置 isProcessing
			isProcessing = false;
		}



		uni.hideLoading()

	}
	const isNowData = (isNowD) => {
		dataArray.value = isNowD;
		console.log('拖拽后更新的', dataArray.value);
		updateAllDayItemOrder();
	}
	const handlePopupOpen = () => {
		isPopupOpen.value = true;
	};

	const handlePopupClose = () => {
		isPopupOpen.value = false;
	};
</script>

<style lang="scss" scoped>
	.no-scroll {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		position: fixed;
	}

	.itempobox {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.isNameCard {
		display: flex;
		flex-direction: column;
		margin-left: 15rpx;
	}

	.isnamecardIndex {
		display: flex;
		margin-top: 15rpx;
		font-size: 24rpx;
		color: #333333;
	}

	.isnamecard {
		font-size: 34rpx;
	}

	.isfix {
		margin-right: 2vw;
		width: 40rpx;
		height: 40rpx;
	}

	.iscardImage {
		margin-left: 2vw;
		border-radius: 10rpx;
		height: 100rpx;
		width: 100rpx;
	}

	.iscardDayBox {

		align-items: center;
		justify-content: space-between;
		display: flex;
		width: 95vw;
		margin: 15rpx auto;
		border-radius: 10rpx;
		height: 20vw;
		border: 1px solid rgb(232, 232, 231);
	}

	.isNo {
		width: 25rpx;
		height: 25rpx;
		border-radius: 50%;
		border: 1px solid black;
	}

	.isselect {
		align-items: center;
		justify-content: center;
		width: 30rpx;
		height: 30rpx;
		/* border-radius: 50%; */
		/* border: 1px solid black; */

	}

	.selectPeleTiem {
		font-size: 28rpx;
		color: #949494;
	}

	.isSelectButton {
		align-items: center;
		justify-content: space-between;
		width: 100%;
		display: flex;
		margin-top: 40rpx;
		margin: 40rpx 0 30rpx 0;
	}

	.isImageIcon {
		margin-left: 10rpx;
	}

	.isIndex {
		margin-left: 10rpx;
		font-size: 28rpx;
		font-weight: 400;
	}

	.isSelectButtonItemBox {
		display: flex;
		align-items: center;

	}

	.isImageIcon {
		width: 30rpx;
		height: 30rpx;
	}

	.isIconImage {
		background-color: rgb(213, 213, 211);
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 13vw;
		left: 5vw;
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
	}

	.isImageBackGourd {
		width: 100vw;
	}

	.isImageBackGourdiMAGE {
		width: 100vw;
	}

	.isTitleIndexBox {
		height: 70rpx;
		width: 160rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		color: white;
		border-radius: 60rpx;
		background-color: rgba(157, 157, 157, 0.8);
	}

	.icon {
		width: 35rpx;
		height: 35rpx;
	}

	.isTitle {
		width: 100%;
		display: flex;
		align-items: center;
		height: 17vw;
		justify-content: space-between;
	}

	.isTitleIndex {
		display: flex;
		flex-wrap: wrap;
		font-size: 31rpx;
		color: #f6f6f6;
		word-wrap: break-word;
		/* 允许长单词断行 */
		overflow-wrap: break-word;
		/* 允许长单词断行，兼容性更好 */
		max-width: 65vw;
		/* 设置一个固定的宽度，以便测试换行效果 */
	}

	.isALLbox {
		width: 95vw;
		display: flex;
		flex-direction: column;
		margin: -140rpx auto;
	}

	.isBackIcon {
		width: 30rpx;
		height: 30rpx;

	}

	.collapsec-box {
		max-height: 1000rpx;
		width: 100%;
		// margin: 40rpx 0rpx;
		padding: 24rpx;
		box-sizing: border-box;
		border-radius: 18rpx;
		border: 2rpx solid rgba(227, 227, 227, 0.5);
		transition: max-height 0.6s ease;
		/* 高度和透明度过渡 */
		overflow: hidden;
		/* 防止内容溢出 */
	}

	.collapsec-box-close {
		max-height: 200rpx;
		/* transition: max-height 0.3s ease; */
		/* 高度和透明度过渡 */
		overflow: hidden;
		/* 防止内容溢出 */
	}

	.Close-box {
		display: flex;
		align-items: center;
	}

	.Close-lt {
		padding: 10rpx 10rpx;
		border-right: 4rpx dashed rgba(191, 191, 191, 1);
		font-size: 24rpx;
		font-weight: 400;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.Close-lt-open {
		color: rgba(4, 75, 173, 1);
	}

	.Close-lt text {
		font-size: 32rpx;
		font-weight: 400;
	}

	.Close-lt-open text {
		color: rgba(4, 75, 173, 1);
	}

	.Close-rt {
		width: 100%;
		display: flex;
		flex-direction: column;
		padding: 0 20rpx;
		box-sizing: border-box;
	}

	.lt-hd {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.hd-title {
		display: flex;
		flex-direction: column;
		font-size: 24rpx;
		font-weight: 400;
		color: rgba(0, 0, 0, 1);
	}

	.hd-title-open {
		color: rgba(4, 75, 173, 1);
	}

	.hd-title text {
		font-size: 28rpx;
		font-weight: 500;
		color: rgba(0, 0, 0, 1);
	}

	.hd-title-open text {
		color: rgba(4, 75, 173, 1);
	}

	.hd-open .close {
		width: 40rpx;
		height: 40rpx;
	}

	.hd-open .open {
		width: 40rpx;
		height: 40rpx;
		-moz-transform: rotate(-180deg);
		-webkit-transform: rotate(-180deg);
	}

	.lt-fd {
		font-size: 20rpx;
		font-weight: 400;
		color: rgba(166, 166, 166, 1);
	}

	.content-container {
		margin-top: 20rpx;

	}

	.content-box {
		padding: 0rpx 20rpx 0rpx 80rpx;
		margin: 30rpx 0;
		box-sizing: border-box;
		border-left: 4rpx dashed rgba(191, 191, 191, 1);
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.content-box .title {
		font-size: 24rpx;
		font-weight: 400;
		color: rgba(0, 0, 0, 1);
	}

	.content-box .content {
		font-size: 20rpx;
		font-weight: 400;
		color: rgba(166, 166, 166, 1);
	}

	.scroll-Y {
		min-height: 30vh;
		max-height: 60vh;

		.text-box {
			margin-bottom: 20rpx;
			color: #000;
		}

	}

	.goods-card {
		width: 100%;
		height: 240rpx;
		display: inline-flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		box-sizing: border-box;
		border-radius: 20rpx;
		background-color: #fff;
		border: 2rpx solid rgba(186, 186, 186, .5);
		margin-bottom: 10rpx;

		.card-img {
			min-width: 36%;
			max-width: 36%;
			height: 100%;
			border-radius: 10rpx;
		}

		.card-right {
			min-width: 56%;
			max-width: 56%;
			height: 220rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			text {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: pre-wrap;
			}

			.title {
				-webkit-line-clamp: 2;
				line-height: 52rpx;
				font-weight: 600;
			}

			.description {
				-webkit-line-clamp: 1;
				font-size: 26rpx;
				color: #8a8a8a;
				// margin: 20rpx 0;
			}

			.price-box {
				text {
					display: inline;
					line-height: 52rpx;
				}

				.price {
					font-weight: 600;
					margin-right: 10rpx;
				}

				.suffix {
					color: #8a8a8a;
					font-size: 18rpx;
				}
			}
		}
	}
</style>